package threads;

import java.io.*;
import java.util.StringTokenizer;

import data.CustomerInfo;
import rm2.DRSserverinit;
import rm2.UDPDatagram;
import exception.BuyToManyException;
//import exception.ItemIsFullException;
import exception.ItemNotExistsException;

import exception.CustomerNotExistsException;

public class ReturnItem// extends Thread
{
	String customer, item;
	int number;
	CustomerInfo cl;
	ItemDeduction ca;
	DRSserverinit drSserverinit;
	 
	public ReturnItem(String customer_id, String item_id, int number,DRSserverinit drSserverinit) 
	{
		// TODO Auto-generated constructor stub
		this.customer = customer_id;
		this.item = item_id;
		//this.ca = ca;
		this.number = number;
		this.drSserverinit=drSserverinit;
		//this.start();
	}
	
	public String Return()
	{		
		int message = 0;
		try
		{
			
			if(drSserverinit.slist.get(item) == null)
			{
				String reply; 
				reply = UDPDatagram.messageSendAndReceive("return~" + this.customer + "~" + item + "~" + this.number,
						this.drSserverinit.closest_1_server_udp_port, this.drSserverinit.closest_1_server_address);
				
				if(reply.contains("unsuccessful"))
				{
					reply = UDPDatagram.messageSendAndReceive("return~" + this.customer + "~" + item + "~" + this.number,
							this.drSserverinit.closest_2_server_udp_port, this.drSserverinit.closest_2_server_address);
				}
				
				if(reply.contains("unsuccessful"))
					throw new ItemNotExistsException(this.customer + " --> Returning" + ": " + "Item: " + item + " does not exist.");
				else
					message = 1;
			}				
			//throw new ItemNotExistsException(this.customer + " --> Buying" + ": " + "Item: " + item + " does not exist.");
			

		
			File file = new File(this.drSserverinit.input_folder_path + File.separator + "CustomerFile" + File.separator + customer);
			String customer="";

			String reserved="";
			int numberOfItems = 0;
			
			if (file.exists())
			{			
				
				ca = new ItemDeduction(this.drSserverinit);
				//System.out.println("test3");
				synchronized (drSserverinit.slist) 
				{
					ca.removeItem(this.customer, this.item, this.number);
					message = 1;
					System.out.println(this.customer  +" returned " + this.number + " unit(s) of " + this.item);
				}
				
				
			}
			else
				throw new CustomerNotExistsException(this.customer  +" --> Cancel" + ": " + " Customer does not exist.");
			//End of FileExist
		}
		catch (Exception e) 
		{
			System.out.println(e.getMessage());
		}
		return Integer.toString(message);
		
	}

}
